/********************************************************/
/*	Copyright (C) 2016 Gong Li Bin		 	*/
/*	Project:	GoLib-1.0.0			*/
/*	Author:		gong_libin			*/
/*	Date:		2016_01_01			*/
/*	File:		GoUdp.go			*/
/********************************************************/

package GoNet

import (
	"net"
)

const (
	GO_UP_UDPA	string = "udp"
	GO_UP_UDP4	string = "udp4"
	GO_UP_UDP6	string = "udp6"
)

type GoUdp struct {
	cn	*net.UDPConn
	ad	*net.UDPAddr
}

func (u *GoUdp) __UdpAddr(n string, a string) (err error) {
	u.ad, err = net.ResolveUDPAddr(n, a)
	return err
}

func (u *GoUdp) GoUdpClose() {
	u.cn.Close()
}

func (u *GoUdp) GoUdpConn() *net.UDPConn {
	return u.cn
}

func (u *GoUdp) GoUdpAddr() *net.UDPAddr {
	return u.ad
}

func (u *GoUdp) GoUdpRead(b []byte) (int, error) {
	return u.cn.Read(b)
}

func (u *GoUdp) GoUdpWrite(b []byte) (int, error) {
	return u.cn.Write(b)
}

func (u *GoUdp) GoUdpSend(b []byte) (i int, e error) {
	return u.cn.WriteToUDP(b, u.ad)
}

func (u *GoUdp) GoUdpRecv(b []byte) (i int, e error) {
	i, u.ad, e = u.cn.ReadFromUDP(b)
	return i, e
}

func (u *GoUdp) GoUdpDial(n string, a string) (err error) {
	if nil == u.__UdpAddr(n, a) {
		u.cn, err = net.DialUDP(n, nil, u.ad)
	}
	return err
}

func (u *GoUdp) GoUdpListen(n string, a string) (err error) {
	if nil == u.__UdpAddr(n, a) {
		u.cn, err = net.ListenUDP(n, u.ad)
	}
	return err
}

/* Multicast */
func (u *GoUdp) GoUdpMulticast(n string, a string) (err error) {
	if nil == u.__UdpAddr(n, a) {
		u.cn, err = net.ListenMulticastUDP(n, nil, u.ad)
	}
	return err
}
